// 显示股票详情
function showStockDetail(stockCode, stockName) {
    currentStockCode = stockCode;
    $('#stockDetailTitle').text(`${stockName} 详情`);
    $('#stockDetailModal').modal('show');

    // 获取实时股票数据
    $.ajax({
        url: `/api/stocks/detail/${stockCode}`,
        method: 'GET',
        success: function (res) {
            if (res.code === "0000") {
                const stock = res.data;
                $('#detailCode').text(stock.code);
                $('#detailName').text(stock.name);
                $('#detailPrice').text(stock.price);

                const changeClass = stock.changePercent >= 0 ? 'positive' : 'negative';
                const changeSymbol = stock.changePercent >= 0 ? '+' : '';
                $('#detailChange').html(`<span class="${changeClass}">${changeSymbol}${stock.changePercent}%</span>`);

                // 显示更多实时数据
                $('#openPrice').text(stock.startPrice);
                $('#highPrice').text(stock.highPrice);
                $('#lowPrice').text(stock.lowPrice);
                $('#volume').text(stock.volume);
            }
        }
    });

    // 初始化图表
    const timeSeriesChartDom = document.getElementById('timeSeriesChart');
    const fundFlowChartDom = document.getElementById('fundFlowChart');
    const dailyChartDom = document.getElementById('dailyChart');

    const timeSeriesChart = echarts.init(timeSeriesChartDom);
    const fundFlowChart = echarts.init(fundFlowChartDom);
    const dailyChart = echarts.init(dailyChartDom);

    // 设置图表标题
    $('#stockDetailModal').on('shown.bs.modal', function () {
        timeSeriesChart.resize();
        fundFlowChart.resize();
        dailyChart.resize();
    });

    // 窗口大小改变时重置图表大小
    $(window).on('resize', function () {
        if ($('#stockDetailModal').hasClass('show')) {
            setTimeout(function () {
                timeSeriesChart.resize();
                fundFlowChart.resize();
                dailyChart.resize();
            }, 100);
        }
    });

    // 获取并显示分时线数据
    $.ajax({
        url: `/api/stocks/minutedata/${stockCode}`,
        method: 'GET',
        success: function (res) {
            if (res.code === "0000") {
                const minuteData = res.data;

                // 准备分时线数据
                // 格式化时间显示
                const formattedTimeList = minuteData.timeList.map(time => {
                    // 将 "0930" 格式化为 "09:30"
                    if (typeof time === 'string' && time.length === 4) {
                        return time.substring(0, 2) + ':' + time.substring(2);
                    }
                    return time;
                });

                // 分时线配置
                const timeSeriesOption = {
                    title: {
                        text: '分钟涨幅',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: function (params) {
                            let result = params[0].axisValue + '<br/>';
                            params.forEach(param => {
                                result += param.marker + param.seriesName + ': ' + param.value.toFixed(2) + ' %<br/>';
                            });
                            return result;
                        }
                    },
                    xAxis: {
                        type: 'category',
                        name: '时间',
                        data: formattedTimeList,
                        axisLabel: {
                            rotate: 45,
                            fontSize: 10
                        }
                    },
                    yAxis: {
                        type: 'value',
                        name: '涨幅(%)',
                        scale: true,
                        axisLabel: {
                            formatter: function (value) {
                                return value.toFixed(2);
                            }
                        }
                    },
                    grid: {
                        left: '10%',
                        right: '10%',
                        bottom: '15%'
                    },
                    series: [{
                        name: '涨幅',
                        type: 'line',
                        data: minuteData.changePercentList,
                        smooth: true,
                        showSymbol: false,
                        lineStyle: {
                            width: 2
                        },
                        areaStyle: {
                            color: 'rgba(255, 0, 0, 0.1)'
                        },
                        itemStyle: {
                            color: 'red'
                        }
                    }]
                };

                timeSeriesChart.setOption(timeSeriesOption);

                // 准备资金流入数据
                // 格式化时间显示
                const fundFlowXAxisData = minuteData.timeList.map(time => {
                    // 将 "0930" 格式化为 "09:30"
                    if (typeof time === 'string' && time.length === 4) {
                        return time.substring(0, 2) + ':' + time.substring(2);
                    }
                    return time;
                });

                // 资金流入图表配置
                const fundFlowOption = {
                    title: {
                        text: '资金流入情况',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: function (params) {
                            let result = params[0].axisValue + '<br/>';
                            params.forEach(param => {
                                // 将元转换为万显示
                                const valueInWan = param.value;
                                result += param.marker + param.seriesName + ': ' + valueInWan.toFixed(2) + ' 万<br/>';
                            });
                            return result;
                        }
                    },
                    legend: {
                        data: ['主力净流入', '超大单净流入', '大单净流入', '中单净流入', '小单净流入'],
                        top: '10%'
                    },
                    xAxis: {
                        type: 'category',
                        name: '时间',
                        data: fundFlowXAxisData,
                        axisLabel: {
                            rotate: 45,
                            fontSize: 10
                        }
                    },
                    yAxis: {
                        type: 'value',
                        name: '资金流入(万)'
                    },
                    grid: {
                        left: '10%',
                        right: '10%',
                        bottom: '15%',
                        top: '20%'
                    },
                    series: [
                        {
                            name: '主力净流入',
                            type: 'line',
                            data: minuteData.mainNetInflow.map(value => value / 10000), // 转换为万
                            smooth: true,
                            showSymbol: false,
                            lineStyle: {
                                width: 2
                            }
                        },
                        {
                            name: '超大单净流入',
                            type: 'line',
                            data: minuteData.superNetInflow.map(value => value / 10000), // 转换为万
                            smooth: true,
                            showSymbol: false
                        },
                        {
                            name: '大单净流入',
                            type: 'line',
                            data: minuteData.bigNetInflow.map(value => value / 10000), // 转换为万
                            smooth: true,
                            showSymbol: false
                        },
                        {
                            name: '中单净流入',
                            type: 'line',
                            data: minuteData.normalNetInflow.map(value => value / 10000), // 转换为万
                            smooth: true,
                            showSymbol: false
                        },
                        {
                            name: '小单净流入',
                            type: 'line',
                            data: minuteData.smallNetInflow.map(value => value / 10000), // 转换为万
                            smooth: true,
                            showSymbol: false
                        }
                    ]
                };

                fundFlowChart.setOption(fundFlowOption);
            }
        },
        error: function () {
            console.error('获取分时线数据失败');
        }
    });
}

// 显示移动股票对话框
function showMoveStockDialog(stockCode, stockName) {
    $.ajax({
        url: '/stockGroup/groupList',
        method: 'GET',
        success: function (res) {
            if (res.code === "0000") {
                // 移除当前分组
                const groups = res.data.filter(g => g.id != currentGroupId);

                if (groups.length === 0) {
                    showToast('没有其他可移动的分组', 'warning');
                    return;
                }

                const groupSelect = $('<select class="form-select mb-3" id="moveGroupSelect"></select>');
                groups.forEach(group => {
                    groupSelect.append(`<option value="${group.id}">${group.name}</option>`);
                });

                const dialog = $(`
                    <div class="modal fade" id="moveStockModal" tabindex="-1">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title">移动股票</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                </div>
                                <div class="modal-body">
                                    <p>将股票 <strong>${stockName}</strong> 移动到以下分组：</p>
                                    ${groupSelect.prop('outerHTML')}
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                    <button type="button" class="btn btn-primary" id="confirmMoveBtn">确认移动</button>
                                </div>
                            </div>
                        </div>
                    </div>
                `);

                $('body').append(dialog);
                $('#moveStockModal').modal('show');

                // 确认移动按钮事件
                $('#confirmMoveBtn').click(function () {
                    const toGroupId = $('#moveGroupSelect').val();
                    moveStockToGroup(stockCode, currentGroupId, toGroupId);
                    $('#moveStockModal').modal('hide');
                });

                // 模态框关闭后销毁
                $('#moveStockModal').on('hidden.bs.modal', function () {
                    $(this).remove();
                });
            }
        }
    });
}

// 移动股票到另一分组
function moveStockToGroup(stockCode, fromGroupId, toGroupId) {
    $.ajax({
        url: `/stockGroup/move/${fromGroupId}/${stockCode}/${toGroupId}`,
        method: 'GET',
        success: function (res) {
            if (res.code === "0000") {
                loadGroupStocks(fromGroupId);
                showToast('股票移动成功', 'success');
            } else {
                showToast('移动失败: ' + res.msg, 'error');
            }
        },
        error: function () {
            showToast('网络错误，请重试', 'error');
        }
    });
}

// 从分组中移除股票
function removeStockFromGroup(stockCode, groupId) {
    $.ajax({
        url: `/stockGroup/remove/${groupId}/${stockCode}`,
        method: 'DELETE',
        success: function (res) {
            if (res.code === "0000") {
                loadGroupStocks(groupId);
                showToast('股票移除成功', 'success');
            } else {
                showToast('移除失败: ' + res.msg, 'error');
            }
        },
        error: function () {
            showToast('网络错误，请重试', 'error');
        }
    });
}